import Mock from 'mockjs';
import { useMockStore } from "@/stores/MockDataBase.js";

// 案件内存数据库
const mockCaseDatabase = (() => {
    // 生成案件数据
    const generateCases = () => {
        return Mock.mock({
            'list|50-100': [
                {
                    'id|+1': 1000,
                    'caseNo': 'CASE-@date("yyMMdd")@integer(1000,9999)',
                    'caseName': '@ctitle(6, 12)',
                    'caseType|1': ['civil', 'criminal', 'administrative', 'commercial'],
                    'applicant': '@cname',
                    'phone': /1[3-9]\d{9}/,
                    'address': '@county(true)',
                    'description': '@csentence(10, 20)',
                    'content': '@cparagraph(20, 50)',
                    'status|1': ['draft', 'reviewing', 'approved', 'rejected', 'processing', 'completed'],
                    'priority|1': ['high', 'normal', 'low'],
                    'realName': '@cname',
                    'attachments|0-5': [
                        {
                            'id|+1': 1,
                            'name': '@ctitle(3, 8).@fileExt("doc,docx,pdf,jpg,png")',
                            'url': '@url("http")',
                            'size': '@integer(1024, 1024000)'
                        }
                    ],
                    'approvals|0-3': [
                        {
                            'id|+1': 1,
                            'approver': '@cname',
                            'status|1': ['approved', 'rejected'],
                            'comment': '@csentence(5, 10)',
                            'time': '@datetime'
                        }
                    ],
                    'createTime': '@datetime',
                    'updateTime': '@datetime'
                }
            ]
        }).list;
    };

    return {
        cases: generateCases(),
        currentCase: null
    };
})();

/**
 * 案件模块Mock配置
 * @param {MockAdapter} mock - Mock适配器实例
 */
export default function(mock) {
    const mockStore = useMockStore();

    // 设置初始案件数据
    mockStore.setCases(mockCaseDatabase.cases);

    // 获取案件列表（带分页）
    mock.onGet('/getCaseList').reply(config => {
        const { page = 1, size = 10, ...query } = config.params || {};
        const start = (page - 1) * size;
        const end = start + size;

        // 过滤逻辑
        let filteredCases = [...mockCaseDatabase.cases];
        // 案件名称过滤
        if (query.caseName) {
            filteredCases = filteredCases.filter(c =>
                c.caseName.includes(query.caseName)
            );
        }

        // 案件类型过滤
        if (query.caseType) {
            filteredCases = filteredCases.filter(c =>
                c.caseType === query.caseType
            );
        }

        // 状态过滤
        if (query.status) {
            filteredCases = filteredCases.filter(c =>
                c.status === query.status
            );
        }

        // 申请人过滤
        if (query.applicant) {
            filteredCases = filteredCases.filter(c =>
                c.applicant.includes(query.applicant)
            );
        }

        // 时间范围过滤
        if (query.startDate && query.endDate) {
            filteredCases = filteredCases.filter(c => {
                const createTime = new Date(c.createTime).getTime();
                const start = new Date(query.startDate).getTime();
                const end = new Date(query.endDate).getTime();
                return createTime >= start && createTime <= end;
            });
        }

        // 分页
        const paginated = filteredCases.slice(start, end);

        return [200, {
            code: 200,
            data: paginated,
            pagination: {
                page: Number(page),
                size: Number(size),
                total: filteredCases.length,
                totalPages: Math.ceil(filteredCases.length / size)
            }
        }];
    });

    // 获取单个案件详情
    mock.onGet(/\/getCaseInfo\/\d+$/).reply(config => {
        const caseId = config.url.split('/').pop();
        const caseItem = mockCaseDatabase.cases.find(c => c.id == caseId);

        if (!caseItem) {
            return [404, {
                code: 404,
                message: '案件不存在'
            }];
        }

        // 设置当前案件
        mockCaseDatabase.currentCase = caseItem;

        return [200, {
            code: 200,
            data: caseItem
        }];
    });

    // 创建案件
    mock.onPost('/cases').reply(config => {
        const newCase = JSON.parse(config.data);
        const maxId = Math.max(...mockCaseDatabase.cases.map(c => c.id), 1000);

        const caseData = {
            id: maxId + 1,
            caseNo: `CASE-${Mock.Random.date('yyMMdd')}${Mock.Random.integer(1000,9999)}`,
            status: 'draft',
            createTime: new Date().toISOString(),
            updateTime: new Date().toISOString(),
            ...newCase
        };

        // 添加到数据库
        mockCaseDatabase.cases.unshift(caseData);
        mockStore.setCases(mockCaseDatabase.cases);

        return [201, {
            code: 201,
            message: '案件创建成功',
            data: caseData
        }];
    });

    // 更新案件
    mock.onPut(/\/updateCase\/\d+$/).reply(config => {
        const caseId = config.url.split('/').pop();
        const updates = JSON.parse(config.data);

        const caseIndex = mockCaseDatabase.cases.findIndex(c => c.id == caseId);

        if (caseIndex === -1) {
            return [404, {
                code: 404,
                message: '案件不存在'
            }];
        }

        // 更新案件
        mockCaseDatabase.cases[caseIndex] = {
            ...mockCaseDatabase.cases[caseIndex],
            ...updates,
            updateTime: new Date().toISOString()
        };

        // 更新当前案件
        if (mockCaseDatabase.currentCase?.id == caseId) {
            mockCaseDatabase.currentCase = mockCaseDatabase.cases[caseIndex];
        }

        // 更新存储
        mockStore.setCases(mockCaseDatabase.cases);

        return [200, {
            code: 200,
            message: '案件更新成功',
            data: mockCaseDatabase.cases[caseIndex]
        }];
    });

    // 删除案件
    mock.onDelete(/\/deleteCase\/\d+$/).reply(config => {
        const caseId = config.url.split('/').pop();
        const originalLength = mockCaseDatabase.cases.length;

        // 过滤掉要删除的案件
        mockCaseDatabase.cases = mockCaseDatabase.cases.filter(c => c.id != caseId);

        // 如果删除了案件，更新存储
        if (mockCaseDatabase.cases.length < originalLength) {
            mockStore.setCases(mockCaseDatabase.cases);

            // 如果删除的是当前案件，清空
            if (mockCaseDatabase.currentCase?.id == caseId) {
                mockCaseDatabase.currentCase = null;
            }

            return [200, {
                code: 200,
                message: '案件删除成功'
            }];
        }

        return [404, {
            code: 404,
            message: '案件不存在或已被删除'
        }];
    });

    // 提交案件审批
    mock.onPost(/\/cases\/\d+\/submit$/).reply(config => {
        const caseId = config.url.split('/')[2];
        const { comment } = JSON.parse(config.data);

        const caseIndex = mockCaseDatabase.cases.findIndex(c => c.id == caseId);

        if (caseIndex === -1) {
            return [404, {
                code: 404,
                message: '案件不存在'
            }];
        }

        // 更新案件状态
        mockCaseDatabase.cases[caseIndex].status = 'reviewing';
        mockCaseDatabase.cases[caseIndex].updateTime = new Date().toISOString();

        // 添加审批记录
        const newApproval = {
            id: mockCaseDatabase.cases[caseIndex].approvals.length + 1,
            approver: '审批员',
            status: 'pending',
            comment: comment || '申请提交审批',
            time: new Date().toISOString()
        };

        mockCaseDatabase.cases[caseIndex].approvals.unshift(newApproval);

        // 更新存储
        mockStore.setCases(mockCaseDatabase.cases);

        return [200, {
            code: 200,
            message: '案件提交审批成功',
            data: mockCaseDatabase.cases[caseIndex]
        }];
    });

    // 获取当前案件
    mock.onGet('/currentCase').reply(() => {
        return mockCaseDatabase.currentCase
            ? [200, { code: 200, data: mockCaseDatabase.currentCase }]
            : [404, { code: 404, message: '当前未选中案件' }];
    });

    // 导出案件数据
    mock.onGet('/cases/export').reply(config => {
        const { ids, format = 'xlsx' } = config.params;

        // 模拟导出文件
        const blob = new Blob([`案件导出数据, 时间: ${new Date().toISOString()}`], { type: 'application/octet-stream' });
        const url = URL.createObjectURL(blob);

        return [200, blob, {
            'content-disposition': `attachment; filename="cases_export.${format}"`
        }];
    });

    // 上传附件
    mock.onPost('/cases/attachments').reply(config => {
        // 这里实际应该处理文件上传，但在Mock中我们模拟上传成功
        const file = config.data;
        const fileName = config.headers['content-disposition']?.split('filename=')[1] || 'file_' + Date.now();

        return [200, {
            code: 200,
            data: {
                name: fileName,
                url: Mock.Random.url(),
                size: file.size || Mock.Random.integer(1024, 1024000)
            },
            message: '附件上传成功'
        }];
    });
}